import socket
import json
import base64
import numpy as np
import time
def base64_encode_image(image_path):
    with open(image_path, "rb") as image_file:
        # 读取文件内容
        image_data = image_file.read()
        # 将文件内容转换为Base64编码
        base64_encoded_data = base64.b64encode(image_data)
        # 将Base64编码的二进制数据转换为ASCII文本
        base64_message = base64_encoded_data.decode('utf-8')
        return base64_message

def generate_sample_data():
    # 生成随机的星座图数据
    real_part = np.random.uniform(-3, 3, 100).tolist()
    imag_part = np.random.uniform(-3, 3, 100).tolist()

    # 生成一些示例的信号质量参数
    snr = np.random.uniform(15, 25)
    bler = np.random.uniform(0, 0.1)
    ber = np.random.uniform(0, 0.01)

    # 生成示例的图片数据（这里仅为了演示，实际中应替换为实际图片数据）
    # img_data = base64_encode_image('')
    img_data = ''

    return {
        "real_part": real_part,
        "imag_part": imag_part,
        "SNR": snr,
        "BLER": bler,
        "BER": ber,
        "PICTURE": img_data,
    }

        
def handle_client(client_socket):
    buf = b""
    while True:
        data = client_socket.recv(4096)
        if not data:
            break
        buf += data
        if b"\r\n\r\n" in buf:
            request = buf.decode("utf-8")
            print(f"Received: {request}")

            if "USRPCONNECT" in request:
                # 解析 JSON 数据并处理 USRP 配置
                try:
                    json_data = json.loads(request.split("\r\n\r\n", 1)[1])
                    print("USRP Config:", json_data)
                except json.JSONDecodeError:
                    print("Error decoding JSON")

                # 假设配置成功
                response = "USRPCONNECT 200\r\n\r\n"
                client_socket.send(response.encode("utf-8"))

            elif "SINGLEREQ" in request:
                sample_data = generate_sample_data()
                response = f"SINGLEREQ 200\r\n\n\n\n{json.dumps(sample_data)}"
                client_socket.send(response.encode("utf-8"))

            elif "CONTINUOUSREQ" in request or "CONTINUOUSREQ2" in request:
                print("Continuous request received")
                counts = 0
                while counts <= 15:
                    counts += 1
                    sample_data = generate_sample_data()
                    response = f"CONTINUOUSREQ 200\r\n\n\n\n{json.dumps(sample_data)}"
                    client_socket.send(response.encode("utf-8"))
                    time.sleep(1)  # 每秒发送一次数据

            else:
                response = "Unknown command\r\n\r\n\r\n"
                client_socket.send(response.encode("utf-8"))

            buf = b""

    client_socket.close()


def tcp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 8000))
    server.listen(5)
    print("Server listening on 127.0.0.1:8000")

    while True:
        client_socket, addr = server.accept()
        print(f"Accepted connection from {addr}")
        handle_client(client_socket)


if __name__ == "__main__":
    tcp_server()
